package com.example.aspect;

/**
 * com.example.aspect.DataSourceAspect
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/30 22:12
 */

import com.example.annotation.DataSource;
import com.example.utils.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {

    // 切入点：拦截所有带有 @DataSource 注解的方法
    @Pointcut("@annotation(com.example.annotation.DataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        // 获取方法上的 @DataSource 注解
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            // 设置数据源类型
            DataSourceContextHolder.setDataSourceType(dataSource.value());
        }

        try {
            // 执行方法
            return point.proceed();
        } finally {
            // 清除数据源类型
            DataSourceContextHolder.clearDataSourceType();
        }
    }
}
